import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";

// 创建 axios 实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE || "http://localhost:8080", // 从环境变量读取
  timeout: 10000,
  headers: { "Content-Type": "application/json" },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    console.log("[Axios] 请求发出:", config.method?.toUpperCase(), config.url);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 后端统一返回 { success, message, errorCode, data }
    if (!res.success) {
      ElMessage.error(res.message || "请求出错");
      return Promise.reject(new Error(res.message || "Error"));
    }
    return res; // 返回完整响应，包含 success, message, data 等字段
  },
  (error) => {
    const { response } = error;
    if (response) {
      const status = response.status;
      let msg = error.message;

      // 处理常见HTTP状态码
      if (status === 401) {
        msg = "未登录或登录已过期";
        // 清除本地存储的token
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        router.push("/login");
      } else if (status === 403) {
        msg = "没有权限访问该资源";
      } else if (status === 404) {
        msg = "请求的资源不存在";
      } else if (status >= 500) {
        msg = "服务器错误，请稍后再试";
      }

      ElMessage.error(msg);
    } else {
      ElMessage.error("网络错误或服务器无响应");
    }
    return Promise.reject(error);
  }
);

export default request;
